package com.example.auction.util;

import android.annotation.SuppressLint;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import com.example.auction.R;
import com.example.auction.activity.RegisterActivity;
import com.example.auction.bean.Item;
import com.example.auction.sqlite.Sqlite;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.*;

public class MyUtil {

    //根据id返回用户名
    @SuppressLint("Range")
    public static String getUserNameByID(Context context, Integer userId) {
        Sqlite sqlite = new Sqlite(context);
        Cursor cursor = sqlite.selectUser(userId);
        String username = "";
        if (cursor != null && cursor.moveToFirst()) {
            username = cursor.getString(cursor.getColumnIndex("user_name"));
        }
        return username;
    }

    //根据id返回用户手机号
    @SuppressLint("Range")
    public static String getUserPhoneByID(Context context, Integer userId) {
        Sqlite sqlite = new Sqlite(context);
        Cursor cursor = sqlite.selectUser(userId);
        String user_phone = "";
        if (cursor != null && cursor.moveToFirst()) {
            user_phone = cursor.getString(cursor.getColumnIndex("user_phone"));
        }
        return user_phone;
    }

    //根据id返回bitmap图片
    @SuppressLint("Range")
    public static Bitmap getImageBySQL(Context context, String user_or_item, Integer user_or_item_id) {
        Sqlite sqlite = new Sqlite(context);
        String flag = user_or_item;
        Cursor cursor;
        byte[] imagedata;
        Bitmap imagebm = null;

        if (flag.equals("user")) {
            cursor = sqlite.selectByID("Auction_user", "user_id", user_or_item_id);
            if (cursor.moveToNext()) {
                imagedata = cursor.getBlob(cursor.getColumnIndex("user_image"));
                imagebm = BitmapFactory.decodeByteArray(imagedata, 0, imagedata.length);
            }
        }
        if (flag.equals("item")) {
            cursor = sqlite.selectByID("Auction_item", "item_id", user_or_item_id);
            if (cursor.moveToNext()) {
                imagedata = cursor.getBlob(cursor.getColumnIndex("item_image"));
                imagebm = BitmapFactory.decodeByteArray(imagedata, 0, imagedata.length);
            }
        }
        return imagebm;
    }

    //比较两个日期之间是否相差多少天
    public static Boolean compareDate(String dateString1, String dateString2, int day) {
        //返回日期1是否大于等于日期2加上天数day
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd HH:mm");
        Date compareDate = new java.util.Date();
        Calendar calendar = Calendar.getInstance();

        // 这里必须加上try catch
        try {
            //字符串转日期对象
            compareDate = sdf.parse(dateString2);
        } catch (Exception e) {
            e.printStackTrace();
        }
        calendar.setTime(compareDate);
        //在原日期dateString2上增加day天
        calendar.add(Calendar.DAY_OF_MONTH, day);
        //获取增加后的日期对象，再转回字符串
        String compareString = sdf.format(calendar.getTime());
        if (dateString1.compareTo(compareString) >= 0) {
            return true;
        } else {
            return false;
        }
    }


    //把传进来的图片转成byte[]类型，必须是在R里的图片
    public static byte[] getDrawableImgToByte(Context context, int drawable_img) {
        //drawable_img 的值必须是资源文件中的图片
        InputStream is = context.getResources().openRawResource(drawable_img);
        Bitmap mBitmap = BitmapFactory.decodeStream(is);
        //转成byte类型存进数据库
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        mBitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
        //转换成byte才能存进数据库
        byte[] image = baos.toByteArray();

        return image;
    }

    //插入1~3个用户
    public static void insertUserData(Context context, int n) {
        if (n <= 3 && n > 0) {
            Sqlite sqlite = new Sqlite(context);
            //三个用户名
            String[] userNameList = new String[]{"星星", "111", "222"};
            String[] userPhoneList = new String[]{
                    "12345678901", "10987654321", "678901234510"};
            //获取头像
            int[] img = {
                    R.drawable.test_img5,
                    R.drawable.test_img6,
                    R.drawable.test_img7,
            };
            for (int i = 0; i < n; i++) {
                byte[] imgByte = MyUtil.getDrawableImgToByte(context, img[i % 3]);
                //插入数据库
                sqlite.insertUser(imgByte, userNameList[i], "111", userPhoneList[i]);
            }
        }
    }

    //插入n个随机拍卖品信息到数据库
    public static void insertItemData(Context context, int n) {
        Sqlite sqlite = new Sqlite(context);
        String[] kindlist = new String[]{
                "数码", "书籍", "日用", "文具", "服饰", "箱包", "鞋子", "游戏"};
        for (int i = 0; i < n; i++) {
            //创建拍卖品信息
            Item item = newItem(context, kindlist[i % 8], i);
            //插入数据库
            sqlite.insertItem(item);
        }
    }

    //随机新的拍卖品信息item
    private static Item newItem(Context context, String kind, int i) {
        Item item = new Item();
        //获取当前时间
        String addtime = MyUtil.getNowDateString();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd HH:mm");
        //创建结束时间
        Date endtimeDate = new java.util.Date();
        Calendar calendar = Calendar.getInstance();
        // 这里必须加上try catch
        try {
            //字符串转日期对象
            endtimeDate = sdf.parse(addtime);
        } catch (Exception e) {
            e.printStackTrace();
        }
        calendar.setTime(endtimeDate);
        //在原日期dateString2上增加day天
        int day = 1;
        calendar.add(Calendar.DAY_OF_MONTH, day);
        //获取增加后的日期对象，再转回字符串
        String endtime = sdf.format(calendar.getTime());

        //获取图片
        int[] img = {
                R.drawable.test_img2,
                R.drawable.test_img3,
                R.drawable.test_img4,
                R.drawable.test_img5,
                R.drawable.test_img6,
                R.drawable.test_img7,
        };

        byte[] imgByte = MyUtil.getDrawableImgToByte(context, img[i % 6]);
        //获取随机价格
        Random random = new Random();
        Integer initPrice = random.nextInt(200) + 1 + i;
        Integer markupPrice = initPrice / 5;

        item.setImage(imgByte);
        item.setItemName("拍卖品" + (i + 1));
        item.setItemDesc("嘎嘎棒" + (i + 1));
        item.setAddtime(addtime);
        item.setEndtime(endtime);
        item.setInitPrice(initPrice.toString());
        item.setMarkupPrice(markupPrice.toString());
        //发布时的最高价等于发布价
        item.setMaxPrice(initPrice.toString());
        item.setOwnerId(2);
        item.setKind(kind);
        item.setWinnerId(0);
        item.setItemRemark(null);
        item.setOwnerVisible(1);
        item.setWinnerVisible(1);
        item.setState("审核中");

        return item;
    }

    //获取当前时间并返回时间字符串
    public static String getNowDateString() {
//        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd HH:mm");
        java.util.Date nowDate = new java.util.Date(System.currentTimeMillis());
        String nowDateString = sdf.format(nowDate);
        return nowDateString;
    }

    public static int dp2px(Context context, int dp) {
        //dp转px公式
        final float scale = context.getResources().getDisplayMetrics().density;
        return ((int) (dp * scale + 0.5f));
    }
}
